package com.fingard.dsp.bank.directbank.srcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParamBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParamBean;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author XueJy on 2018/8/21.
 * @version 1.0
 */
public class SRCB01Base extends DirectBase {
    private static final String DEFAULTENCODING = "UTF-8";
    private static final String REQUEST_CONTENT_TYPE = "text/xml";
    private static HttpClient httpclient;
    private String session_id = "";

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    public void afterPropertiesSet() throws Exception {
        HttpParams params = new BasicHttpParams();
        setClientParam(params);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8000));
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpclient = new DefaultHttpClient(cm, params);
    }

    private void setClientParam(HttpParams params) {
        /**
         * 1��������� 2ȡ�����ӳ�ʱʱ��
         * */
        ConnManagerParamBean connManagerParamBean = new ConnManagerParamBean(params);
        connManagerParamBean.setMaxTotalConnections(10);
        connManagerParamBean.setTimeout(10000);
        /**
         * HttpЭ��汾
         * */
        HttpProtocolParamBean protocolParamBean = new HttpProtocolParamBean(params);
        protocolParamBean.setVersion(HttpVersion.HTTP_1_1);
        /**
         * 1���ӳ�ʱʱ�� 2��Ӧ��ʱʱ��
         * */
        HttpConnectionParamBean httpConnectionParamBean = new HttpConnectionParamBean(params);
        httpConnectionParamBean.setConnectionTimeout(10000);
        httpConnectionParamBean.setSoTimeout(60000);
    }


    public String[] sendToBank(String[] filePath) throws Exception {
        String requestURL = bankFront.serverURL;
        afterPropertiesSet();
        WriteBankUrlLogLn(requestURL);
        HttpPost httpPost = new HttpPost(requestURL);
        /**
         * ģ��ͻ��˵��ϴ��ļ���������һ����ʱ�򣬾�ͨ���ϴ��ļ��ķ�ʽ�ϴ�
         */
        if (filePath.length == 1) {
            StringEntity stringEntity = new StringEntity(filePath[0], "UTF-8");
            stringEntity.setContentEncoding(DEFAULTENCODING);
            stringEntity.setContentType(REQUEST_CONTENT_TYPE);
            httpPost.setEntity(stringEntity);
            /**
             * ģ��ͻ��˵��ļ���������1����ʱ�򣬾�ͨ��ಿ���ϴ�
             * */
        } else {
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setCharset(Charset.forName("utf-8"));
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            File f = null;
            for (String path : filePath) {
                f = new File(path);
                if (f.exists()) {
                    FileBody fileBody = new FileBody(f);
                    entityBuilder.addPart(f.getName(), fileBody);
                }
            }

            httpPost = new HttpPost(requestURL);
            httpPost.setEntity(entityBuilder.build());
        }
        String responseString = null;
        try {
            HttpResponse httpResponse = httpclient.execute(httpPost, new BasicHttpContext());
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                responseString = new String(bytes, DEFAULTENCODING);
                WriteBankLogStep3(responseString);
                return new String[]{"", responseString};
            } else {
                WriteBankLogLn("文件上传失败");
                return new String[]{"-1", "文件上传失败"};
            }
        } catch (Exception e) {
            httpPost.abort();
            responseString = e.getCause().toString();
            return new String[]{"-1", responseString};
        }
    }

//    public String[] sendToBank2(String[] filePath) throws Exception {
//        String requestURL = bankFront.serverURL;
//        setHttpClient();
//        WriteBankUrlLogLn(requestURL);
//        HttpPost httpPost = new HttpPost(requestURL);
//        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
//        entityBuilder.setCharset(Charset.forName("UTF-8"));
//        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
//        //������
//        for (String path : filePath) {
//            File f = new File(path);
//            if (f.exists()) {
//                entityBuilder.addPart(f.getName(), new FileBody(f));
//            }
//        }
//        httpPost.setEntity(entityBuilder.build());
//        String responseString = null;
//        try {
//            HttpResponse httpResponse = httpclient.execute(httpPost, new BasicHttpContext());
//            HttpEntity entity = httpResponse.getEntity();
//            if (entity != null) {
//                byte[] bytes = EntityUtils.toByteArray(entity);
//                responseString = new String(bytes, DEFAULTENCODING);
//                WriteBankLogStep3(responseString);
//                return new String[]{"", responseString};
//            } else {
//                return new String[]{"-1", "���ͺ�δ��������"};
//            }
//        } catch (Exception e) {
//            httpPost.abort();
//            responseString = e.getCause().toString();
//            return new String[]{"-1", responseString};
//        }
//    }


    public String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        String httpUrl = "";
        httpUrl = bankFront.serverURL;
        WriteBankLogLn("提交银行的地址为：" + httpUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpRequest = new WebRequest(httpUrl);
        tmpRequest.setRequestProperty("accept", "text/xml");
        String charsetName = getCharset();
        byte[] tmpWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }


    void writeCommonHeader(XmlTextWriter xmlWriter, String transCode, String packetId) {
        /* <request >
            <head >
                <packet_id >12345000</packet_id >
                <tran_code > 0000 </tran_code >
                <session_id ></session_id >
             </head >*/
        xmlWriter.writeStartDocByDeclaration("<?xml version = \"1.0\" encoding = \"UTF-8\" ?>");
        xmlWriter.writeStartElement("request");
        xmlWriter.writeStartElement("head");
        if (StringHelper.isNullOrEmpty(packetId)){
            xmlWriter.writeElementString("packet_id", Format.Date8Format.format(new Date()) + getBankConfig().getValueAsString("packet_id"));
        } else {
            xmlWriter.writeElementString("packet_id", packetId);
        }
        xmlWriter.writeElementString("tran_code", transCode);
        xmlWriter.writeElementString("session_id", session_id);
        xmlWriter.writeEndElement();
    }

    void writeBodyParams(XmlTextWriter xmlWriter, List<String[]> params) {
           /* <body >
             <parameter >
                 <name > LoginID </name >
                 <value > 21100662413802 </value >
            </parameter >
            <parameter >
                 <name > LoginPWD </name >
                 <value > yYSu0BSux2I6VPBZHaB6hf1Ldi0 =</value >
             </parameter >
            </body>
        </request>*/
        xmlWriter.writeStartElement("body");
        for (String[] param : params) {
            xmlWriter.writeStartElement("parameter");
            xmlWriter.writeElementString("name", param[0]);
            xmlWriter.writeElementString("value", param[1]);
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();

    }

    String[] login() throws Exception {
  /*<?xml version = "1.0" encoding = "UTF-8" ?>
         <request >
            <head >
                <packet_id >12345000</packet_id >
                <tran_code > 0000 </tran_code >
                <session_id ></session_id >
             </head >
             <body >
             <parameter >
                 <name > LoginID </name >
                 <value > 21100662413802 </value >
            </parameter >
            <parameter >
                 <name > LoginPWD </name >
                 <value > yYSu0BSux2I6VPBZHaB6hf1Ldi0 =</value >
             </parameter >
            </body>
        </request>
        */
        XmlTextWriter xmlTextWriter = new XmlTextWriter();
        writeCommonHeader(xmlTextWriter, "0000","");
        List<String[]> params = new ArrayList<String[]>();
        //�������
        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
        mdTemp.update(bankFront.loginPasswd.getBytes());
        String pwdEncoded= Base64Helper.getBase64(mdTemp.digest());
        //��½�û�������
        params.add(new String[]{"LoginID", bankFront.loginName});
        params.add(new String[]{"LoginPWD", pwdEncoded});
        //д�뱨����
        writeBodyParams(xmlTextWriter, params);
        String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            String tmpRetCode = tmpBkReader.getFirstText("/response/head/ret_code");
            if ("000000".equals(tmpRetCode)) {
                //��½�ɹ�
                session_id = tmpBkReader.getFirstText("/response/body/session_id");
                WriteBankLogLn("session_id获取成功");
            } else if ("SE60002".equals(tmpRetCode)) {
                //��½�ɹ�,��������
                session_id = tmpBkReader.getFirstText("/response/body/session_id");
                WriteBankLogLn("服务费即将到期");
            } else {
                WriteBankLogLn("session_id获取失败" + tmpBkReader.getFirstText("/response/head/err_msg"));
                return new String[]{"-1",tmpBkReader.getFirstText("/response/head/err_msg")};
            }
            return tmpStrRet;
        } else {
            WriteBankLogLn("session_id获取失败" + tmpStrRet[1]);
            return tmpStrRet;
        }
    }



}
